<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link type="text/css" href="resources/css/main.css" 			rel="stylesheet"/>
	
	
	
<script type="text/javascript">
		/* ---------------------------------------------- */
var currentItemId;
var currentRowData;
		
$(function(){ 
	//alert("GO");
	/* ------------------ GRID FUNCTION ----------------- */	
  $("#listPrivate").jqGrid({
	jsonReader : {
	      root:"rows",
	      page: "page",
	      total: "total",
	      records: "records",
	      repeatitems: false,
	      id: "0"
	   },	  
    url:'json/entity/b',
    datatype: 'json',
    mtype: 'POST',
    ondblClickRow: function(rowid){showItemCard(rowid);},
    colNames:['','#','Инв.№', 'Носитель №','Фото','Тип носителя','','AB','Район','Нас.пункт', 'Адрес', 'Описание расположения','Статус', 'Цена',  'Ширина','Высота','Размеры', 'Свободно'],
    colModel :[ 
      {name:'id', 					index:'id', 				width:20, hidden:true}, 
      {name:'chk_itemSelected', 	index:'chk_itemSelected', 	width:20, formatter: checkBoxFormatter},     	  
//       {name:'chk_itemSelected',index:'chk_itemSelected', width:15, align:"right",edittype:'checkbox',formatter: "checkbox",editoptions: { value:"True:False"},editable:true,formatoptions: {disabled : false}},
        
      {name:'inventarNr', 	   		index:'inventarNr', 		width:40, hidden:true, search:true},
      {name:'supportNr',			index:'supportNr', 			width:50, hidden:true},
      {name:'photo', 				index:'photo',				width:120, 
    	  formatter: photoFormatter, sortable:false },      
      {name:'supportTypeName',		index:'supportTypeName',	width:90, align:'center' },
      {name:'light', 				index:'light',				width:25, align:'center',
    	  formatter: lightFormatter, sortable:false, fixed:true },
      {name:'AB', 	   				index:'AB', 				width:40,  align:'center', sortable:false, formatter: partFormatter},    	  
      {name:'regionName', 			index:'regionName', 		width:90}, 
      {name:'localityName', 		index:'localityName', 		width:100}, 
      {name:'adress', 				index:'adress',				width:130, sortable:false},
      {name:'locationDescription', 	index:'locationDescription',width:220},
      {name:'status', 				index:'status',				width:30,  hidden:true },
      {name:'price_base', 			index:'price_base',			width:45, 
    	  formatter:priceFormatter , align:'center' },
      {name:'width', 				index:'width',				width:45, sortable:false, hidden:true},
      {name:'height', 				index:'height',				width:45, sortable:false, hidden:true},
      {name:'dimension', 			index:'dimension',			width:70, sortable:false, fixed:true,
    	  formatter: dimensionFormatter},
      {name:'firstFreeDate', 				index:'firstFreeDate',				width:80, sortable:false}
    ],
    pager: '#pager',
    toppager: true,
    altRows: false,
    rowNum:10,
    rowList:[10,20,30],
    sortname: 'id',
    sortorder: 'asc',
    viewrecords: true,
    gridview: true,
    autowidth: true,
    height: 'auto',
    caption: 'Рекламные площади',
    search: true,
    postData: 	{ filters:{	supportType:		function() { return $('#pSupportType').val(); }, 
						   	regionName: 		function() { return $('#pRegionName').val(); },
						   	localityName: 		function() { return $('#pLocalityName').val(); },
							addresString: 		function() { return $('#pAddresString').val(); },
						 	light: 				function() { return $('#pLight').is(':checked'); },
						 	priceFrom: 			function() { return $('#pPriceFrom').val(); },
						 	priceTo: 			function() { return $('#pPriceTo').val(); },
						 	freeOnDate:			function() { return $('#pFreeOnDate').val(); } 
							}
				}
  }); 
	
  function checkBoxFormatter(cellvalue, options, rowObject) {
	  return "<input type='checkbox' id=cb_" + rowObject['id'] + ">"; 
	  };
	
	
  function photoFormatter(cellvalue, options, rowObject) {
	  return "<img src='images/small/" + rowObject['inventarNr'] + "' width='120' alt='Фото' title='Фото' />";
	  };   
  
  function priceFormatter(cellvalue, options, rowObject) {
      return cellvalue + " \u20AC";
  };   	 
  
  
  function lightFormatter(cellvalue, options, rowObject) {
	  if (rowObject['light']){
		  return "<img src='resources/icons/lightbulb_on.png' width='14' alt='+' title='+' />";
	  }  else {
		  return "<img src='resources/icons/lightbulb.png' width='14' alt='-' title='-' />";
	  }
  };    
  
  function dimensionFormatter(cellvalue, options, rowObject) {
	  return rowObject['width'] + 'm.X' + rowObject['height']+'m.';
  };     
  
  function partFormatter(cellvalue, options, rowObject) {
	  var inv = rowObject['inventarNr'];
	  var sup = rowObject['supportNr'];
	  return inv.replace(sup,'');
	//  return rowObject['supportNr'].replace(rowObject['supportNr'],'');
  };  
  
  
  $("#basketContent").jqGrid({
		jsonReader : {
		      root:"rows",
		      page: "page",
		      total: "total",
		      records: "records",
		      repeatitems: false,
		      id: "0"
		   },	  
	    url:'json/entity/userBasket/listTotal',
	    datatype: 'json',
	    mtype: 'POST',
	    colNames:['Тип носителя','Сумма', 'Количество'],
	    colModel :[ 
	      {name:'supportTypeName',		index:'supportTypeName',	width:90, align:'center', sortable:false},
	      {name:'sum', 					index:'sum',				width:45, align:'center', sortable:false},
	      {name:'count', 				index:'count',				width:45, align:'center', sortable:false}
	    ],
	    pager: '#pager',
	    altRows: false,
	    rowNum:10,
	    rowList:[10,20,30],
	    sortname: 'supportTypeName',
	    sortorder: 'asc',
	    viewrecords: true,
	    gridview: true,
	    autowidth: true,
	    height: 'auto',
	    caption: ''
	  }); 
  
  
// Item Card Functionality  
  function showItemCard(rowId) {
	
	var rowData = $("#listPrivate").getRowData(rowId);
	var colData = rowData['locationDescription'];
	
	//$("#cardLocationDescription").val(colData);
	//alert("colData = " + colData);
	
	currentItemId = rowId;
	currentRowData = rowData;
	$( "#itemDetail" ).dialog( "open" );
  };
  
  
  $(function() {
      $( "#itemDetail" ).dialog({
          autoOpen: false,
          height: 600,
          width: 	900,
          resizable: false,
          modal: true,
          buttons: {
              "Добавить в корзину": 	function() {
            	  addToBasket(this);
              	//$( this ).dialog( "close" );
              }
          },
          close: function() {
              //allFields.val( "" ).removeClass( "ui-state-error" );
          },
          open: function(){
              //var note_text = $('#pRegionName').attr('type');
             $("#cardItemId").html(currentRowData['id']);
             $("#cardInventarNr").html(currentRowData['inventarNr']);
             $("#cardSupportType").html(currentRowData['supportTypeName']);
             $("#cardLight").html(currentRowData['light']);             
             $("#cardWidthHeight").html(currentRowData['width'] + "m.X" + currentRowData['height'] + "m.");
             $("#cardPriceBase").html(currentRowData['price_base']);
             $("#cardRegionName").html(currentRowData['regionName']);	 
             $("#cardLocalityName").html(currentRowData['localityName']);
             $("#cardAdress").html(currentRowData['adress']);

             $("#cardLocationDescription").html(currentRowData['locationDescription']);
             $("#cardFirstFreeDate").html(currentRowData['firstFreeDate']);
             
             $("#cardTitle").html(currentRowData['inventarNr'] + "  &nbsp;&nbsp;&nbsp;&nbsp;" + 
            		 			  currentRowData['supportTypeName'] + "  &nbsp;&nbsp;&nbsp;&nbsp;" +
            		 			  currentRowData['width'] + "m.X" + currentRowData['height'] + "m.  &nbsp;&nbsp;&nbsp;&nbsp;" +
            		 			  currentRowData['light'] + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
            		 			  currentRowData['price_base'] + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
            		 			  currentRowData['firstFreeDate']);
             
             $("#cardLocation").html(currentRowData['localityName'] + "  " + 
		 			  				 currentRowData['adress']);
             
             $("#cardPhoto").attr('src',"images/big/" + currentRowData['inventarNr']);
             $("#map_canvas").gmap({ 'center': '47.013388,28.837698', 'zoom': 17 });
             
          }
      });
});

  

  
  /* ------------------ FILTERS FUNCTION ----------------- */	  
 	
	$("#btResetFilter").click(function(){
		$("#pSupportType").val("");
		$("#pRegionName").val("");
		$("#pLocalityName").val("");
		$("#pAddresString").val("");
		$("#pLight").attr('checked', false);
		$("#pPriceFrom").val("");
		$("#pPriceTo").val("");
		$("#pFreeOnDate").val("");
		
		$("#listPrivate").trigger("reloadGrid");
	});
	
	$("#btApplyFilter").click(function(){
		$("#listPrivate").trigger("reloadGrid");
	});
	
	// Add AUTOCOMPLETE functionality for filters panel
	
	 $("#pRegionName").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/region",
		                   dataType : "json",
		                   data : {
		                	   style: "full",
		                        maxRows: 12,
		                	   term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.regionName,
		                               value : item.regionName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });			
	
	 
	 $("#pLocalityName").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/locality",
		                   dataType : "json",
		                   data : {
		                       term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.localityName,
		                               value : item.localityName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });
	 
	 $("#pSupportType").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/supportType",
		                   dataType : "json",
		                   data : {
		                       term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.supportTypeName,
		                               value : item.supportTypeName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });

//Add AUTOCOMPLETE functionality for filters panel	

  function addToBasket(refDialog) {  
	  //alert($("#cardFirstFreeDate").html());
	  var requestAdd = 'json/entity/userBasket/add'; //?itemId=' + $("#cardItemId").html()+'&firstFreeDate=' + $("#cardFirstFreeDate").html();
	  $.ajax({
	          url : requestAdd,
	          dataType : "json",
	          data : {
	        	  itemId : $("#cardItemId").html(),
	        	  firstFreeDate : $("#cardFirstFreeDate").html()
	          		},
	          success : function(data) {
	        	  $("#basketContent").trigger("reloadGrid");
	        	  refreshBasketTotal();
	          		}
      	});
	  
	  $(refDialog).dialog( "close" );
  };
  



	  $( "#submitAll").button().click(function() {
		  
		  var rows= jQuery("#listPrivate").jqGrid('getRowData');
			
		  if (rows.length<1){
			  return;
		  }
		  
    	  var requestAdd = 'json/entity/userBasket/add';
    	  $(rows).each(function(i, row){
    		  var checkbox = $("#cb_" + row['id'], "#listPrivate");
		      if ($(checkbox).is(":checked")){
//			      $('<input type="text" />').attr('name', i+'_name').attr('value', row['id']).appendTo("#hiddenDiv");
		    	  $.ajax({
		    	          url : requestAdd,
		    	          dataType : "json",
		    	          data : {
		    	        	  itemId : row['id'],
		    	        	  firstFreeDate :row['firstFreeDate']
		    	          		},
		    	          success : function(data) {
		    	        	  //console.log(checkbox);
		    	        	 	$(checkbox).removeAttr("checked").trigger('change');
		    	      	 		$("#basketContent").trigger("reloadGrid");
		    	        	  	refreshBasketTotal();
		    	          		}
		          	});  
			      }	
    	  });
  	 		//$("#basketContent").trigger("reloadGrid");
    	  	//refreshBasketTotal();
    	  	//$("#listPrivate").trigger("reloadGrid");
	    });
	  


   $( "#pFreeOnDate" ).datepicker({
   	dateFormat: "dd.mm.yy",
   	autoSize: true,
       changeMonth: true,
       changeYear: true,
       showOn: "button",
       buttonImage: "resources/css/images/calendar.gif",
       buttonImageOnly: true,
       showButtonPanel: true,
       defaultDate: "+1w"
   });	  
	  
	  
}); 
	
	
	
function refreshBasketTotal() {
	  //$("#totalString").$("#cardAdress").html(currentRowData['adress']); 
	  $.getJSON('json/entity/userBasket/listSumTotal', function(data) {
		  $("#totalString").html("Итого :  " + data + " \u20AC");
		});
};	

	


$(document).ready(refreshBasketTotal);

</script>
</head>	
<body>

<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"
			style="padding: .2em .2em .2em .2em;" >
	<span class="ui-jqgrid-title" style="font-size: 0.9em;">Фильтрационные параметры</span>
</div>
<div id="filtrationPanel" class="ui-userdata ui-state-default" style="padding: .2em .2em .2em .2em;">
	<table id="prm" style="width: 100%" border="0">
		<tr>
			<td align="right">Тип носителя:</td>
			<td><input type="text" id="pSupportType" class="ui-widget"></td>
			<td>&nbsp;</td>
			<td align="right">Регион:</td>
			<td><input type="text" id="pRegionName" class="ui-widget" ></td>
			<td>&nbsp;</td>
			<td align="right">Нас.пункт:</td>
			<td colspan="2">
				<input type="text" id="pLocalityName"  class="ui-widget" >
				</td>
<!-- 						<td>&nbsp;</td> -->
			<td align="right">&nbsp;</td>
			<td><input id="btApplyFilter" type="button" value="Отфильтровать"></td>
		</tr>
		<tr>
			<td align="right">Свободен на:</td>
			<td><input type="text" id="pFreeOnDate" class="ui-widget"></td>						
			<td>&nbsp;</td>
			<td align="right">Адрес:</td>
			<td><input type="text" id="pAddresString" class="ui-widget"></td>
			<td>&nbsp;</td>
			<td align="right">Цена:</td>
			<td>
				<input type="text" id="pPriceFrom" class="ui-widget" size="7">
				<input type="text" id="pPriceTo"   class="ui-widget" size="7">
			</td>
			<td>Освещение:</td>
			<td align="right"><input type="checkbox" id="pLight" ></td>
			<td><input id="btResetFilter" type="button" value="Очистить фильтр"></td>
		</tr>	

	</table> 
</div>
<br>
<table style="width: 100%;" >
	<tr>
		<td align="center" width="100%" >
			<table id="listPrivate">
				<tr><td/></tr>
			</table>
		</td>
		<td align="center" valign="top"> 
			<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"
				style="padding: .2em .2em .2em .2em;width: 250px;" >
			<span class="ui-jqgrid-title" style="font-size: 0.9em;">Содержимое корзины:</span>
			</div>
			<div id="basketPanel" 
				class="ui-userdata ui-state-default" 
				style="padding: .2em .2em .2em .2em; height: 150px;">
				<table id="basketContent">
					<tr><td/></tr>
				</table>
				<span id="totalString"></span>	
			 </div>
			<div><button id="submitAll">Добавить в корзину</button></div>
			<div id="hiddenDiv"></div>
<!-- 			<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix" -->
<!-- 				style="padding: .2em .2em .2em .2em;width: 250px;" > -->
<!-- 			<span class="ui-jqgrid-title" style="font-size: 0.9em;">Position deatails:</span> -->
<!-- 			</div> -->
<!-- 			<div id="detailsPanel"  -->
<!-- 				class="ui-userdata ui-state-default"  -->
<!-- 				style="padding: .2em .2em .2em .2em; height: 200px;"> </div>			 -->
 		</td>
	</tr>
</table>

<div id="itemDetail" title="Детали рекламной площади" style="font-size: 0.9em;">
	<table style="width: 100%;">
		<tr><td colspan="2"><div id="cardTitle" align="left" ></div></td></tr>
		<tr><td colspan="2"><div id="cardLocation" align="left" ></div></td></tr>		
		<tr>
			<td><a> <img id="cardPhoto" src='' width="500" alt='Photo' title='PHOTO' /></a></td>
			<td>
			<div id="cardItemId" hidden="hidden" ></div>
			<div id="cardFirstFreeDate" hidden="hidden" ></div>
			
			<div id="map_canvas" style="width:350px;height:350px"></div>
			</td>		
		</tr>
		
		<tr><td colspan="2" align="left">Описание расположения :		</td></tr>
		<tr><td colspan="2"><div id="cardLocationDescription"></div></td></tr>
	</table>
</div>

</body>
</html>